package com.wx.tnsadmin.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wx.tnsadmin.mapper.UmsAdminMapper;
import com.wx.tnsadmin.model.UmsAdminModel;
import com.wx.tnsadmin.model.UmsAuthModel;
import com.wx.tnsadmin.model.UmsRoleModel;
import com.wx.tnsadmin.service.UmsAdminService;
import com.wx.tnsadmin.utils.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * @Author:LLH
 * @Date:2020/8/10
 */
@Service
@Slf4j
public class UmsAdminServiceImpl implements UmsAdminService {

    private static final Logger LOGGER = LoggerFactory.getLogger ( UmsAdminServiceImpl.class );

    @Autowired
    private UmsAdminMapper umsAdminMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;


//    /**
//     * token过期时间，2天
//     */
//    public static final int TOKEN_EXPIRE = 3600 * 24 * 2;
//
//    @Autowired
//    private RedisUtil redisUtil;


    public String loginAdmin ( String username,String password ) {


        String token = null;
        try {
            UserDetails userDetails = userDetailsService.loadUserByUsername ( username );
            if (!passwordEncoder.matches ( password,userDetails.getPassword ( ) )) {
                throw new BadCredentialsException ( "密码不正确" );
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken ( userDetails,null,userDetails.getAuthorities ( ) );
            SecurityContextHolder.getContext ( ).setAuthentication ( authentication );
            token = jwtTokenUtil.generateToken ( userDetails );

        } catch (UsernameNotFoundException e) {
            e.printStackTrace ( );
        } catch (BadCredentialsException e) {
            e.printStackTrace ( );
            LOGGER.warn ( "登录异常:{}",e.getMessage ( ) );
        }
        return token;
    }

//    @Override
//    public UmsAdminModel getByToken ( HttpServletResponse response,String token ) {
//        if (StringUtils.isEmpty(token)) {
//            return null;
//        }
//        UmsAdminModel user = JSON.parseObject(redisUtil.get(token + "::" + token), UmsAdminModel.class);
//        //重置有效期
//        if (user == null) {
//            throw new GlobalException ( CodeMsg.USER_NOT_LOGIN);
//        }
//        addCookie(response, token, user);
//        return user;
//    }
//    private void addCookie(HttpServletResponse response, String token, UmsAdminModel user) {
//        //将token存入到redis
//        redisUtil.set(token + "::" + token, JSON.toJSONString(user), TOKEN_EXPIRE);
//        //将token写入cookie
//        Cookie cookie = new Cookie(token, token);
//        cookie.setMaxAge(TOKEN_EXPIRE);
//        cookie.setPath("/");
//        response.addCookie(cookie);
//    }
//


    @Override
    public List<UmsAdminModel> findAllAdmin () {
        return umsAdminMapper.findAllAdmin ( );
    }

    @Override
    public UmsAdminModel findByAdminId ( String id ) {
        return umsAdminMapper.findByAdminId ( id );
    }

    @Override
    public Integer saveAdmin ( UmsAdminModel umsAdminModel ) {
        return umsAdminMapper.saveAdmin ( umsAdminModel );
    }

    @Override
    public Integer updateAdmin ( UmsAdminModel umsAdminModel ) {
        return umsAdminMapper.updateAdmin ( umsAdminModel );
    }

    @Override
    public Integer deleteAdminById ( String id ) {
        return umsAdminMapper.deleteAdminById ( id );
    }

    @Override
    public PageInfo findByAdminPage ( UmsAdminModel umsAdminModel ) {
        PageHelper.startPage ( umsAdminModel.getPageNum ( ),umsAdminModel.getPageSize ( ) );
        List<UmsAdminModel> list = umsAdminMapper.findByAdminPage ( umsAdminModel );
        PageInfo pageInfo = new PageInfo ( list );
        return pageInfo;
    }

    @Override
    public Integer deleteAdminUpdate ( String id ) {
        return umsAdminMapper.deleteAdminUpdate ( id );
    }

    @Override
    public Integer deleteAdminAllById ( List<String> id ) {
        HashMap<String, List<String>> map = new HashMap<> ( );
        map.put ( "id",id );
        return umsAdminMapper.deleteAdminAllById ( map );
    }

    @Override
    public Integer updateByPassword ( String username,String newpassword ) {
        return umsAdminMapper.updateByPassword ( username,newpassword );
    }

    @Override
    public UmsAdminModel findByUsername ( String username ) {
        return umsAdminMapper.findByUsername ( username );
    }

    @Override
    public List<UmsAuthModel> getAuthList ( String username ) {
        return umsAdminMapper.getAuthList ( username );
    }

    @Override
    public List<UmsRoleModel> getUserRoleByUserName ( String username ) {
        return umsAdminMapper.getUserRoleByUserName ( username );
    }

}
